<!--
  ~
  ~  Copyright (c) 2018-2025, Pactera JinXin Software All rights reserved.
  ~
  -->

<template>
    <div class="app-container calendar-list-container">
        <basic-container>
            <template>
                <el-row>
                    <el-col :span="12">
                        <el-tabs v-model="switchStatus">
                            <el-tab-pane label="信息管理" name="userManager">
                                <el-form ref="ruleForm2" :model="ruleForm2" :rules="rules2" label-width="100px" class="demo-ruleForm">
                                    <el-form-item label="员工号" prop="username">
                                        <el-input v-model.trim="ruleForm2.username" type="text" disabled />
                                    </el-form-item>
                                    <el-form-item label="手机号" prop="phone">
                                        <el-input v-model.trim="ruleForm2.phone" disabled />
                                    </el-form-item>
                                    <el-form-item label="头像">
                                        <el-upload :headers="headers" :show-file-list="false" :on-success="handleAvatarSuccess" class="avatar-uploader" action="/admin/sys-file/upload">
                                            <img v-if="ruleForm2.avatar" id="avatar" :src="avatarUrl" class="avatar" />
                                            <div v-else class="avatar-uploader-icon">
                                                <i class="el-icon-plus" />
                                            </div>
                                        </el-upload>
                                    </el-form-item>
                                    <el-form-item>
                                        <el-button type="primary" @click="submitForm('ruleForm2')">提交</el-button>
                                        <el-button @click="resetForm('ruleForm2')">重置</el-button>
                                    </el-form-item>
                                </el-form>
                            </el-tab-pane>
                            <el-tab-pane label="密码管理" name="passwordManager">
                                <el-form v-if="switchStatus === 'passwordManager'" ref="ruleForm2" :model="ruleForm2" :rules="rules2" label-width="100px" class="demo-ruleForm">
                                    <el-form-item label="原密码" prop="password">
                                        <el-input v-model.trim="ruleForm2.password" type="password" auto-complete="off" maxlength="16" />
                                    </el-form-item>
                                    <el-form-item label="新密码" prop="newpassword1">
                                        <el-input v-model.trim="ruleForm2.newpassword1" type="password" auto-complete="off" maxlength="16" />
                                    </el-form-item>
                                    <el-form-item label="确认密码" prop="newpassword2">
                                        <el-input v-model.trim="ruleForm2.newpassword2" type="password" auto-complete="off" maxlength="16" />
                                    </el-form-item>
                                    <el-form-item>
                                        <el-button type="primary" @click="submitForm('ruleForm2')">提交</el-button>
                                        <el-button @click="resetForm('ruleForm2')">重置</el-button>
                                    </el-form-item>
                                </el-form>
                            </el-tab-pane>
                        </el-tabs>
                    </el-col>
                </el-row>
            </template>
        </basic-container>
    </div>
</template>

<script>
import { handleImg, openWindow } from '@/util/util';
import { mapState } from 'vuex';
import store from '@/store';
import { getStore } from '@/util/store';
import request from '@/router/axios';

export default {
    data() {
        let validatePass = (rule, value, callback) => {
            if (this.ruleForm2.password !== '') {
                if (value !== this.ruleForm2.newpassword1) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };
        let validatePwd = (rule, value, callback) => {
            let num = 0,
                rep1 = /[A-Z]/g, // 大写字母
                rep2 = /[a-z]/g, // 小写字母
                rep3 = /[~!@￥#$%^&*()_+{}:"<>?/*-+~！@#￥%…&*（）—=｛｝|《》？]/g;
            rep1.test(value) ? num++ : '';
            rep2.test(value) ? num++ : '';
            rep3.test(value) ? num++ : '';
            if (num >= 2) {
                callback();
            } else {
                callback(new Error('大小写字母和特殊符号，不少于两种!'));
            }
        };
        return {
            switchStatus: 'userManager', // 视图展示条件
            avatarUrl: '', // 头像url
            show: false, // 显示开关
            // 请求头
            headers: {
                Authorization: 'Bearer ' + store.getters.access_token
            },
            // 表单对象
            ruleForm2: {
                username: '',
                password: '',
                newpassword1: '',
                newpassword2: '',
                avatar: '',
                phone: ''
            },
            // 表单校验规则
            rules2: {
                password: [
                    {
                        required: true,
                        min: 8,
                        message: '密码长度为8-16位',
                        trigger: 'change'
                    },
                    {
                        required: true,
                        validator: validatePwd,
                        trigger: 'change'
                    }
                ],
                newpassword1: [
                    {
                        required: true,
                        min: 8,
                        message: '密码长度为8-16位',
                        trigger: 'change'
                    },
                    {
                        required: true,
                        validator: validatePwd,
                        trigger: 'change'
                    }
                ],
                newpassword2: [
                    {
                        required: true,
                        min: 8,
                        message: '密码长度为8-16位',
                        trigger: 'change'
                    },
                    {
                        required: true,
                        validator: validatePass,
                        trigger: 'blur'
                    }
                ]
            }
        };
    },
    created() {
        this.resetForm();
    },
    computed: {
        ...mapState({
            userInfo: (state) => state.user.userInfo
        })
    },
    methods: {
        // 获取用户个人信息
        getUserInfo() {
            this.$store.dispatch('GetUserInfo').then(() => {});
        },
        // 点击tab
        switchTab(tab) {
            if (tab.name === 'userManager') {
                handleImg(this.ruleForm2.avatar, 'avatar');
            }
            this.switchStatus = tab.name;
        },
        // 点击提交
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    request({
                        url: '/admin/user/edit',
                        method: 'put',
                        data: this.ruleForm2
                    })
                        .then((response) => {
                            if (response.data.data) {
                                this.$notify.success('修改成功');
                                // 修改密码之后强制重新登录
                                if (this.switchStatus === 'passwordManager') {
                                    this.$store.dispatch('LogOut').then(() => {
                                        location.reload(); // 为了重新实例化vue-router对象 避免bug
                                    });
                                }
                                this.getUserInfo();
                            } else {
                                this.$notify.error(response.data.msg);
                            }
                        })
                        .catch(() => {
                            this.$notify.error('修改失败');
                        });
                } else {
                    return false;
                }
            });
        },
        // 点击重置
        resetForm(formName) {
            this.ruleForm2.password = undefined;
            this.ruleForm2.newpassword1 = undefined;
            this.ruleForm2.newpassword2 = undefined;
            this.ruleForm2.username = this.userInfo.username;
            this.ruleForm2.phone = this.userInfo.phone;
            this.ruleForm2.avatar = this.userInfo.avatar;
            handleImg(this.userInfo.avatar, 'avatar');
            //判断是否选择了租户ID
            const TENANT_ID = getStore({ name: 'tenantId' });
            if (TENANT_ID) {
                this.headers['TENANT-ID'] = TENANT_ID; // 租户ID
            }
        },
        // 上传头像成功回调
        handleAvatarSuccess(res, file) {
            this.avatarUrl = URL.createObjectURL(file.raw);
            this.ruleForm2.avatar = res.data.url;
        }
    }
};
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px !important;
    color: #8c939d !important;
    width: 178px !important;
    height: 178px !important;
    line-height: 178px !important;
    text-align: center !important;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
